package com.example.tellwin.mine.act;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Rect;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.apkfuns.logutils.LogUtils;
import com.example.tellwin.MainApplication;
import com.example.tellwin.PhotoActivity;
import com.example.tellwin.R;
import com.example.tellwin.base.CpBaseActivty;
import com.example.tellwin.base.DaggerRxComponent;
import com.example.tellwin.common.Common;
import com.example.tellwin.event.OrderDetailEvent;
import com.example.tellwin.event.OrderListEvent;
import com.example.tellwin.event.PayResultEvent;
import com.example.tellwin.home.act.TeacherDetailActivity;
import com.example.tellwin.mine.adapter.OrderPhotoAdapter;
import com.example.tellwin.mine.bean.AuthResult;
import com.example.tellwin.mine.bean.OrderDetailBean;
import com.example.tellwin.mine.bean.PayResult;
import com.example.tellwin.mine.bean.WeChatPayBean;
import com.example.tellwin.mine.contract.OrderDetailContract;
import com.example.tellwin.mine.presenter.OrderDetailPresenter;
import com.example.tellwin.question.act.AnswerActivity;
import com.example.tellwin.question.adapter.VoiceAdapter;
import com.example.tellwin.question.bean.VoiceBean;
import com.example.tellwin.utils.CommonUtils;
import com.example.tellwin.utils.GlideUtils;
import com.example.tellwin.utils.ToastUtil;
import com.example.tellwin.view.ContentTextView;
import com.example.tellwin.view.SelectWheelDialog;
import com.example.tellwin.view.ShareDialog;
import com.hedgehog.ratingbar.RatingBar;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class OrderDetailActivity extends CpBaseActivty implements OrderDetailContract.View {

    @BindView(R.id.order_state_ll)
    LinearLayout orderStateLl;
    @BindView(R.id.order_type_iv)
    ImageView orderTypeIv;
    @BindView(R.id.order_type_tv)
    TextView orderTypeTv;
    @BindView(R.id.order_number_tv)
    ContentTextView orderNumberTv;
    @BindView(R.id.channel_tv)
    ContentTextView channelTv;
    @BindView(R.id.question_tv)
    ContentTextView questionTv;
    @BindView(R.id.question_people_tv)
    ContentTextView questionPeopleTv;
    @BindView(R.id.answer_mode_tv)
    ContentTextView answerModeTv;
    @BindView(R.id.question_describe_tv)
    TextView questionDescribeTv;
    @BindView(R.id.voice_rv)
    RecyclerView voiceRv;
    @BindView(R.id.pic_rv)
    RecyclerView picRv;
    @BindView(R.id.teacher_head_iv)
    ImageView teacherHeadIv;
    @BindView(R.id.teacher_name_tv)
    TextView teacherNameTv;
    @BindView(R.id.solutions_tv)
    TextView solutionsTv;
    @BindView(R.id.solve_time_tv)
    TextView solveTimeTv;
    @BindView(R.id.fee_paid_tv)
    TextView feePaidTv;
    @BindView(R.id.solve_iv)
    ImageView solveIv;
    @BindView(R.id.solve_paly_fl)
    FrameLayout solvePalyFl;
    @BindView(R.id.wechat_pay_iv)
    ImageView wechatPayIv;
    @BindView(R.id.wechat_pay_ll)
    LinearLayout wechatPayLl;
    @BindView(R.id.ali_pay_iv)
    ImageView aliPayIv;
    @BindView(R.id.ali_pay_ll)
    LinearLayout aliPayLl;
    @BindView(R.id.shu_xiu_iv)
    ImageView shuXiuIv;
    @BindView(R.id.shu_xiu_ll)
    LinearLayout shuXiuLl;
    @BindView(R.id.pay_ll)
    LinearLayout payLl;
    @BindView(R.id.satisfaction_rbtn)
    RadioButton satisfactionRbtn;
    @BindView(R.id.common_rbtn)
    RadioButton commonRbtn;
    @BindView(R.id.dissatisfaction_rbtn)
    RadioButton dissatisfactionRbtn;
    @BindView(R.id.comment_rb)
    RatingBar commentRb;
    @BindView(R.id.evaluation_ll)
    LinearLayout evaluationLl;
    @BindView(R.id.evaluation_tv)
    TextView evaluationTv;
    @BindView(R.id.evaluation_iv)
    ImageView evaluationIv;
    @BindView(R.id.evaluation_content_ll)
    LinearLayout evaluationContentLl;
    @BindView(R.id.satisfaction_degree_tv)
    TextView satisfactionDegreeTv;
    @BindView(R.id.commented_rb)
    RatingBar commentedRb;
    @BindView(R.id.writing_evaluation_tv)
    TextView writingEvaluationTv;
    @BindView(R.id.evaluationed_rl)
    RelativeLayout evaluationedRl;
    @BindView(R.id.order_detail_left_btn)
    TextView orderDetailLeftBtn;
    @BindView(R.id.order_detail_right_btn)
    TextView orderDetailRightBtn;
    @BindView(R.id.teacher_rl)
    RelativeLayout teacherRl;
    @BindView(R.id.solve_rl)
    RelativeLayout solveRl;
    @BindView(R.id.solutions_ll)
    LinearLayout solutionsLl;
    @BindView(R.id.payment_method_tv)
    ContentTextView paymentMethodTv;
    @BindView(R.id.commit_btn)
    TextView commitBtn;
    @BindView(R.id.teacher_answer_number_tv)
    TextView teacherAnswerNumberTv;//教师评价
    @BindView(R.id.teacher_rank_tv)
    TextView teacherRankTv;//教师级别
    @BindView(R.id.fee_paid_text)
    TextView feePaidText;

    int type = 1;
    VoiceAdapter voiceAdapter;
    List<VoiceBean> voiceBeans = new ArrayList<>();
    OrderPhotoAdapter photoAdapter;
    List<String> photoPaths = new ArrayList<>();
    SelectWheelDialog selectWheelDialog;
    String[] strings = new String[]{"老师很nice，教学幽默风趣", "很喜欢老师的解题方式", "老师很负责，直到我听懂为止"};

    String payId;
    int payType;

    int score = 0;

    @Inject
    OrderDetailPresenter mPresenter;
    private OrderDetailBean orderDetailBean;

    MediaPlayer mediaPlayer;
    private IWXAPI api;


    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    LogUtils.d(payResult);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        mPresenter.getOrderDetail(orderDetailBean.getOrderId());
                        EventBus.getDefault().post(new OrderListEvent());
                        // mPresenter.payQuery();
                        // showAlert(PayDemoActivity.this, getString(R.string.pay_success) + payResult);
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        LogUtils.d("支付失败");
                        //  showAlert(PayDemoActivity.this, getString(R.string.pay_failed) + payResult);
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        LogUtils.d("授权成功");
                        //   showAlert(PayDemoActivity.this, getString(R.string.auth_success) + authResult);
                    } else {
                        // 其他状态值则为授权失败
                        LogUtils.d("授权失败");
                        //   showAlert(PayDemoActivity.this, getString(R.string.auth_failed) + authResult);
                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_detail);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        api = WXAPIFactory.createWXAPI(this, Common.WeChatPayId, false);
        api.registerApp(Common.WeChatPayId);
        initViews();
        initEvents();
        initDatas();
    }

    @Override
    protected void initViews() {
        DaggerRxComponent.builder()
                .baseAppComponent(MainApplication.getAppComponent())
                .build()
                .inject(this);
        mPresenter.attachView(this);

        mediaPlayer = new MediaPlayer();

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        voiceRv.setLayoutManager(linearLayoutManager);
        voiceRv.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                outRect.top = getResources().getDimensionPixelOffset(R.dimen.dp_10);
            }
        });
        voiceAdapter = new VoiceAdapter();
        voiceRv.setAdapter(voiceAdapter);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        picRv.setLayoutManager(gridLayoutManager);
        picRv.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                int position = parent.getChildAdapterPosition(view);
                if (position % 3 == 0) {
                    outRect.right = getResources().getDimensionPixelOffset(R.dimen.dp_2_5);
                } else if (position % 3 == 1) {
                    outRect.right = getResources().getDimensionPixelOffset(R.dimen.dp_2_5);
                    outRect.left = getResources().getDimensionPixelOffset(R.dimen.dp_2_5);
                } else {
                    outRect.left = getResources().getDimensionPixelOffset(R.dimen.dp_2_5);
                }
                if (position >= 3) {
                    outRect.top = getResources().getDimensionPixelOffset(R.dimen.dp_5);
                }
            }
        });
        photoAdapter = new OrderPhotoAdapter();
        picRv.setAdapter(photoAdapter);
    }

    @Override
    protected void initEvents() {
        wechatPayLl.setOnClickListener(v -> {
            wechatPayIv.setSelected(true);
            aliPayIv.setSelected(false);
            shuXiuIv.setSelected(false);
        });
        aliPayLl.setOnClickListener(v -> {
            wechatPayIv.setSelected(false);
            aliPayIv.setSelected(true);
            shuXiuIv.setSelected(false);
        });
        shuXiuLl.setOnClickListener(v -> {
            wechatPayIv.setSelected(false);
            aliPayIv.setSelected(false);
            shuXiuIv.setSelected(true);
        });
        evaluationLl.setOnClickListener(v -> {
            if (selectWheelDialog == null) {
                selectWheelDialog = new SelectWheelDialog(this);
                selectWheelDialog.setTitle("选择评价");
                selectWheelDialog.setMiddleList(Arrays.asList(strings));
                selectWheelDialog.setOnSelectListener((position, str) -> {
                    evaluationTv.setText(str);
                });
            }
            selectWheelDialog.show();
        });
        voiceAdapter.setOnVoiceItemClick(new VoiceAdapter.OnVoiceItemClick() {
            @Override
            public void onVoiceItemClick(int postion, VoiceBean voiceBean) {
                try {
                    mediaPlayer.stop();
                    mediaPlayer.reset();
                    mediaPlayer.setDataSource(voiceBean.getPath());//设置播放来源
                    mediaPlayer.prepareAsync();//异步准备
                    mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        //异步准备监听
                        @Override
                        public void onPrepared(MediaPlayer mediaPlayer) {
                            mediaPlayer.start();//播放
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onItemDeleteClick(int postion, VoiceBean voiceBean) {

            }
        });
        commentRb.setOnRatingChangeListener(RatingCount -> {
            score = (int) RatingCount;
        });
        photoAdapter.setOnItemClickListener(position -> {
            Intent intent = new Intent(this, PhotoActivity.class);
            intent.putExtra(Common.PHOTO_PATH, new ArrayList<>(photoPaths));
            intent.putExtra(Common.POSITION, position);

            startActivity(intent);
        });
    }

    @Override
    protected void initDatas() {
        setTitle(R.string.order_detail);
        String orderId = getIntent().getStringExtra(Common.ORDER);
        if (TextUtils.isEmpty(orderId)) {
            finish();
            return;
        }
        mPresenter.getOrderDetail(orderId);

    }

    @OnClick({R.id.order_detail_left_btn, R.id.order_detail_right_btn, R.id.commit_btn, R.id.teacher_rl})
    public void onViewClicked(View view) {
        String orderStatus = orderDetailBean.getOrderStatus();
        switch (view.getId()) {
            case R.id.order_detail_left_btn:
                if (MainApplication.Identity.equals(Common.NORMAL)) {
                    if ("1".equals(orderStatus)) {//未解答重新派单
                        mPresenter.sendOrder(orderDetailBean.getOrderId());
                    } else if ("2".equals(orderStatus)) {//已付款，该按钮是分享
                        ShareDialog shareDialog = new ShareDialog(this, 3, orderDetailBean.getOrderId(), orderDetailBean.getQuestionName());
                        shareDialog.show();
                    }
                }
                break;
            case R.id.order_detail_right_btn:
                if (MainApplication.Identity.equals(Common.NORMAL)) {
                    if ("1".equals(orderStatus)) {//立即支付
                        if (wechatPayIv.isSelected()) {
                            payType = 1;
                            mPresenter.orderPay(orderDetailBean.getOrderId(), 1);
                        } else if (aliPayIv.isSelected()) {
                            payType = 2;
                            mPresenter.orderPay(orderDetailBean.getOrderId(), 2);
                        } else if (shuXiuIv.isSelected()) {
                            payType = 3;
                            mPresenter.orderPay(orderDetailBean.getOrderId(), 3);
                        } else {
                            ToastUtil.show(this, "请选择支付方式");
                            return;
                        }
                    } else if ("2".equals(orderStatus)) {//已付款状态，按钮为评价
                        int satisfaction = 0;
                        if (satisfactionRbtn.isChecked()) {
                            satisfaction = 2;
                        } else if (commonRbtn.isChecked()) {
                            satisfaction = 1;
                        } else if (dissatisfactionRbtn.isChecked()) {
                            satisfaction = 0;
                        } else {
                            ToastUtil.show(this, "请选择满意程度！");
                            return;
                        }
                        if (TextUtils.isEmpty(evaluationTv.getText())) {
                            ToastUtil.show(this, "请选择文字评价！");
                            return;
                        }
                        String evaluation = evaluationTv.getText().toString();
                        mPresenter.orderEvaluate(orderDetailBean.getOrderId(), evaluation, satisfaction + "", score + "");
                    }
                }
                break;
            case R.id.commit_btn:
                if (!CommonUtils.requestPermissions(this)) {
                    return;
                }

                if (MainApplication.Identity.equals(Common.NORMAL)) {
                    if ("0".equals(orderStatus) || "5".equals(orderStatus)) {
                        mPresenter.cancelOrder(orderDetailBean.getOrderId());
                    } else if ("4".equals(orderStatus)) {
                        mPresenter.newOrder(orderDetailBean.getOrderId());
                    }
                } else if (MainApplication.Identity.equals(Common.ANSWER)) {
                    if ("0".equals(orderStatus) || "5".equals(orderStatus)) {
                        mPresenter.meetOrder(orderDetailBean.getOrderId());
                    } else if ("2".equals(orderStatus) || "3".equals(orderStatus)) {//分享
                        ShareDialog shareDialog = new ShareDialog(this, 3, orderDetailBean.getOrderId(), orderDetailBean.getQuestionName());
                        shareDialog.show();
                    }
                }
                break;
            case R.id.teacher_rl:
                Intent intent = new Intent(this, TeacherDetailActivity.class);
                intent.putExtra(Common.TEACHER_NAME, orderDetailBean.getRealName());
                intent.putExtra(Common.TEACHER_ID, orderDetailBean.getAnswerUserId());
                startActivity(intent);
                break;
        }
    }

    @Override
    public void orderDetailResult(OrderDetailBean orderDetailBean) {
        this.orderDetailBean = orderDetailBean;
        String orderStatus = orderDetailBean.getOrderStatus();//0待接单1已完成2已付款3已评价4已取消5不满意
        orderNumberTv.setTvStr(CommonUtils.getStr(orderDetailBean.getOrderId()));
        channelTv.setTvStr(CommonUtils.getStr(orderDetailBean.getGradeName()) + " " + CommonUtils.getStr(orderDetailBean.getSubjectName()));
        questionTv.setTvStr(CommonUtils.getStr(orderDetailBean.getAskTitle()));
        questionDescribeTv.setText(CommonUtils.getStr(orderDetailBean.getDescribe()));
        teacherNameTv.setText(CommonUtils.getStr(orderDetailBean.getRealName()));
        teacherAnswerNumberTv.setText(getResources().getString(R.string.teacher_content, CommonUtils.getStr(orderDetailBean.getAnswerCount()), CommonUtils.getStr(orderDetailBean.getSatisfiedCount())));
        GlideUtils.loadHeadImage(this, orderDetailBean.getHeadPic(), teacherHeadIv);
        teacherRankTv.setText(CommonUtils.getStr(orderDetailBean.getQualificationsName()));
        answerModeTv.setTvStr(CommonUtils.getAnswerType(orderDetailBean.getAnswerType()));
        solutionsTv.setText(CommonUtils.getAnswerType(orderDetailBean.getAnswerType()));
        solveTimeTv.setText(Html.fromHtml("<font color= '#D94850'>" + CommonUtils.canParseInt(orderDetailBean.getAnswerDuration()) + "</font>" + "分钟"));

        feePaidTv.setText(Html.fromHtml("<font color= '#D94850'>" + (MainApplication.Identity.equals(Common.ANSWER) ? CommonUtils.getStr(orderDetailBean.getAnswerIncome()) : CommonUtils.getStr(orderDetailBean.getOrderPrice())) + "</font>" + "元"));
        paymentMethodTv.setTvStr(CommonUtils.getPayType(orderDetailBean.getPayType()));
        satisfactionDegreeTv.setText(CommonUtils.getSatisfied(orderDetailBean.getIsSatisfied()));
        commentedRb.setStar(CommonUtils.canParseInt(orderDetailBean.getScore()));
        writingEvaluationTv.setText(CommonUtils.getStr(orderDetailBean.getContent()));
        questionPeopleTv.setTvStr(CommonUtils.getStr(orderDetailBean.getQuestionName()));
        answerModeTv.setTvStr(CommonUtils.getAnswerType(orderDetailBean.getAnswerType()));

        List<OrderDetailBean.OrderFileBean> orderFileBeans = orderDetailBean.getOrderFileList();
        orderDetailLeftBtn.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.sp_16));
        photoPaths.clear();
        voiceBeans.clear();
        for (int i = 0; i < orderFileBeans.size(); i++) {
            if ("1".equals(orderFileBeans.get(i).getFileType())) {//图片
                photoPaths.add(orderFileBeans.get(i).getFileUrl());
            } else if ("2".equals(orderFileBeans.get(i).getFileType())) {//音频
                VoiceBean voiceBean = new VoiceBean();
                voiceBean.setPath(orderFileBeans.get(i).getFileUrl());
                voiceBean.setTime(CommonUtils.canParseInt(orderFileBeans.get(i).getFileSize()));
                voiceBeans.add(voiceBean);
            }
        }
        photoAdapter.setPhotoPaths(photoPaths);
        voiceAdapter.setVoiceBeans(voiceBeans, false);

        if (MainApplication.Identity.equals(Common.NORMAL)) {
            orderStateLl.setVisibility(View.VISIBLE);
            solvePalyFl.setVisibility(View.GONE);
            questionPeopleTv.setVisibility(View.GONE);
            answerModeTv.setVisibility(View.GONE);
            if ("3".equals(orderStatus)) {//订单已评价
                evaluationedRl.setVisibility(View.VISIBLE);
                teacherRl.setVisibility(View.VISIBLE);
                paymentMethodTv.setVisibility(View.VISIBLE);
                solveRl.setVisibility(View.VISIBLE);
                solutionsLl.setVisibility(View.VISIBLE);
                orderDetailLeftBtn.setVisibility(View.VISIBLE);
                orderDetailRightBtn.setVisibility(View.VISIBLE);

                payLl.setVisibility(View.GONE);
                evaluationContentLl.setVisibility(View.GONE);
                commitBtn.setVisibility(View.GONE);


                orderTypeTv.setText(R.string.order_evaluationed);
                orderTypeIv.setImageResource(R.mipmap.details_icon_goods);
                orderDetailLeftBtn.setText(R.string.share);
                orderDetailRightBtn.setText(R.string.evaluation);
                orderDetailRightBtn.setVisibility(View.GONE);
            } else if ("2".equals(orderStatus)) {//订单已付款
                evaluationContentLl.setVisibility(View.VISIBLE);
                teacherRl.setVisibility(View.VISIBLE);
                solveRl.setVisibility(View.VISIBLE);
                orderDetailLeftBtn.setVisibility(View.VISIBLE);
                orderDetailRightBtn.setVisibility(View.VISIBLE);

                evaluationedRl.setVisibility(View.GONE);
                payLl.setVisibility(View.GONE);
                commitBtn.setVisibility(View.GONE);
                feePaidText.setText(R.string.fee_paided);
                orderTypeTv.setText(R.string.order_payed);
                orderTypeIv.setImageResource(R.mipmap.details_icon_payment);
                orderDetailLeftBtn.setText(R.string.share);
                orderDetailRightBtn.setText(R.string.evaluation);
            } else if ("1".equals(orderStatus)) {//订单已完成 ，未解答重新派单

                teacherRl.setVisibility(View.VISIBLE);
                solveRl.setVisibility(View.VISIBLE);
                solutionsLl.setVisibility(View.VISIBLE);
                orderDetailLeftBtn.setVisibility(View.VISIBLE);
                orderDetailRightBtn.setVisibility(View.VISIBLE);
                payLl.setVisibility(View.VISIBLE);

                evaluationContentLl.setVisibility(View.GONE);
                evaluationedRl.setVisibility(View.GONE);
                paymentMethodTv.setVisibility(View.GONE);
                commitBtn.setVisibility(View.GONE);
                feePaidText.setText(R.string.fee_paid);
                orderTypeTv.setText(R.string.order_done);
                orderTypeIv.setImageResource(R.mipmap.details_icon_done);
                orderDetailLeftBtn.setText(R.string.unsolved);
                orderDetailLeftBtn.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.sp_12));
                orderDetailRightBtn.setText(R.string.immediate_payment);

            } else if ("100".equals(orderStatus)) {//订单已完成 ，申述

                teacherRl.setVisibility(View.VISIBLE);
                solveRl.setVisibility(View.VISIBLE);
                solutionsLl.setVisibility(View.VISIBLE);
                orderDetailLeftBtn.setVisibility(View.VISIBLE);
                orderDetailRightBtn.setVisibility(View.VISIBLE);
                payLl.setVisibility(View.VISIBLE);

                evaluationContentLl.setVisibility(View.GONE);
                evaluationedRl.setVisibility(View.GONE);
                paymentMethodTv.setVisibility(View.GONE);
                commitBtn.setVisibility(View.GONE);

                orderTypeTv.setText(R.string.order_done);
                orderTypeIv.setImageResource(R.mipmap.details_icon_done);
                orderDetailLeftBtn.setText(R.string.represention);
                orderDetailRightBtn.setText(R.string.immediate_payment);

            } else if ("4".equals(orderStatus)) {//取消订单
                evaluationedRl.setVisibility(View.GONE);
                payLl.setVisibility(View.GONE);
                orderTypeTv.setText(R.string.order_cancel);
                orderTypeIv.setImageResource(R.mipmap.details_icon_cancle);

                teacherRl.setVisibility(View.GONE);
                evaluationedRl.setVisibility(View.GONE);
                solveRl.setVisibility(View.GONE);
                evaluationContentLl.setVisibility(View.GONE);
                orderDetailLeftBtn.setVisibility(View.GONE);
                orderDetailRightBtn.setVisibility(View.GONE);

                commitBtn.setVisibility(View.VISIBLE);
                commitBtn.setText(R.string.order_again);
            } else if ("0".equals(orderStatus) || "5".equals(orderStatus)) {//等待接单
                evaluationedRl.setVisibility(View.GONE);
                payLl.setVisibility(View.GONE);
                orderTypeTv.setText(R.string.order_wait);
                orderTypeIv.setImageResource(R.mipmap.details_icon_time);

                teacherRl.setVisibility(View.GONE);
                evaluationedRl.setVisibility(View.GONE);
                solveRl.setVisibility(View.GONE);
                evaluationContentLl.setVisibility(View.GONE);
                orderDetailLeftBtn.setVisibility(View.GONE);
                orderDetailRightBtn.setVisibility(View.GONE);

                commitBtn.setVisibility(View.VISIBLE);
                commitBtn.setText(R.string.cancel_order);
            }
            if ("3".equals(orderDetailBean.getAnswerType())) {
                solvePalyFl.setVisibility(View.VISIBLE);
            } else {
                solvePalyFl.setVisibility(View.GONE);
            }
        } else if (MainApplication.Identity.equals(Common.ANSWER)) {
            questionPeopleTv.setVisibility(View.VISIBLE);
            answerModeTv.setVisibility(View.VISIBLE);
            orderStateLl.setVisibility(View.GONE);
            teacherRl.setVisibility(View.GONE);
            solutionsLl.setVisibility(View.GONE);
            payLl.setVisibility(View.GONE);
            evaluationContentLl.setVisibility(View.GONE);
            if ("1".equals(orderStatus)) {//订单完成
                evaluationedRl.setVisibility(View.GONE);
                paymentMethodTv.setVisibility(View.GONE);
                solvePalyFl.setVisibility(View.GONE);

                orderDetailLeftBtn.setText(R.string.share_friend);
                orderDetailRightBtn.setText(R.string.urge_pay);
                orderDetailRightBtn.setBackgroundResource(R.drawable.green_stroke_shape);
                orderDetailRightBtn.setTextColor(getResources().getColor(R.color.theme_color));
                orderDetailRightBtn.setVisibility(View.GONE);
                orderDetailLeftBtn.setVisibility(View.VISIBLE);
                commitBtn.setVisibility(View.GONE);

                solveRl.setVisibility(View.VISIBLE);
            } else if ("2".equals(orderStatus)) {//订单已付款
                evaluationedRl.setVisibility(View.GONE);
                solvePalyFl.setVisibility(View.GONE);
                paymentMethodTv.setVisibility(View.VISIBLE);

                orderDetailRightBtn.setVisibility(View.GONE);
                orderDetailLeftBtn.setVisibility(View.GONE);
                commitBtn.setVisibility(View.VISIBLE);
                commitBtn.setText(R.string.share);

                solveRl.setVisibility(View.VISIBLE);
            } else if ("3".equals(orderStatus)) {//订单已评价
                solvePalyFl.setVisibility(View.GONE);
                paymentMethodTv.setVisibility(View.VISIBLE);

                orderDetailRightBtn.setVisibility(View.GONE);
                orderDetailLeftBtn.setVisibility(View.GONE);
                commitBtn.setVisibility(View.VISIBLE);
                commitBtn.setText(R.string.share);

                evaluationedRl.setVisibility(View.VISIBLE);
                solveRl.setVisibility(View.VISIBLE);
            } else if ("0".equals(orderStatus) || "5".equals(orderStatus)) {//订单未接单
                evaluationedRl.setVisibility(View.GONE);

                orderDetailRightBtn.setVisibility(View.GONE);
                orderDetailLeftBtn.setVisibility(View.GONE);
                commitBtn.setVisibility(View.VISIBLE);
                commitBtn.setText(R.string.answer_);

                evaluationedRl.setVisibility(View.GONE);
                solveRl.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void cancelOrderSuccess() {
        setResult(Common.UPDATE_ORDER_LIST);
        finish();
    }

    @Override
    public void meetOrderResult() {
        Intent intent = new Intent(this, AnswerActivity.class);
        intent.putExtra(Common.ORDER, orderDetailBean);
        startActivity(intent);
    }

    @Override
    public void selectAnswerTypeResult(int type) {
    }

    @Override
    public void sendOrderResult() {
        initDatas();
        EventBus.getDefault().post(new OrderListEvent());
    }

    @Override
    public void onWeChatPay(String payId, WeChatPayBean weChatPayBean) {
        this.payId = payId;
        PayReq req = new PayReq();
        req.appId = weChatPayBean.appid;
        req.partnerId = weChatPayBean.partnerid;
        req.prepayId = weChatPayBean.prepayid;
        req.packageValue = "Sign=WXPay";
        req.nonceStr = weChatPayBean.noncestr;
        req.timeStamp = weChatPayBean.timestamp;
        req.sign = weChatPayBean.sign;
        api.sendReq(req);
    }

    @Override
    public void payQuerySuccess() {
        mPresenter.getOrderDetail(orderDetailBean.getOrderId());
        EventBus.getDefault().post(new OrderListEvent());
    }

    @Override
    public void orderEvaluateSuccess() {
        mPresenter.getOrderDetail(orderDetailBean.getOrderId());
        EventBus.getDefault().post(new OrderListEvent());
    }

    @Override
    public void onAliPay(String data) {
        final Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                //String data = "alipay_sdk=alipay-sdk-java-4.10.209.ALL&app_id=2021002116607548&biz_content=%7B%22body%22%3A%22%E6%88%91%E6%98%AF%E6%B5%8B%E8%AF%95%E6%95%B0%E6%8D%AE%22%2C%22out_trade_no%22%3A%22123%22%2C%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%2C%22subject%22%3A%22App%E6%94%AF%E4%BB%98%E6%B5%8B%E8%AF%95Java%22%2C%22timeout_express%22%3A%2230m%22%2C%22total_amount%22%3A%220.01%22%7D&charset=utf-8&format=json&method=alipay.trade.app.pay&notify_url=%E5%95%86%E6%88%B7%E5%A4%96%E7%BD%91%E5%8F%AF%E4%BB%A5%E8%AE%BF%E9%97%AE%E7%9A%84%E5%BC%82%E6%AD%A5%E5%9C%B0%E5%9D%80&sign=RTujL8XHAb%2Bqz4pS3BK7uPuVFh6KrzCZG%2BLud6Ua6Jalz441j9BBd%2F8IBaW%2FE0iMT%2FQQKUXAXTpsDJXwkgOtjYyUrtaQRpDAT1p%2B1ZlS6ep3uP3E5l8X3Za%2Fz5boOfdtwrSQxPm4OkggnPtuHfMLksLIAlJC0Mu0SU1DctrOghHWprcaRf%2ByC7eSi6dUyL1QVbKlpI177feZ0jgIeEt1hpCxkXeTgA6qAgNB5EXfYhQ03IDRjhxTTGYba4pre0ZYD0MaZNdG7v1T5uObNrrTANv7gNZk42vWF4Wd%2FAxPGFCsAbl%2Fk%2BVaRzhj9EYoEXcmNcQ75tIFAdQjTlJTqAoDWw%3D%3D&sign_type=RSA2&timestamp=2020-12-24+19%3A52%3A33&version=1.0";
                PayTask alipay = new PayTask(OrderDetailActivity.this);
                Map<String, String> result = alipay.payV2(data, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @Override
    public void onBalancePay() {
        mPresenter.getOrderDetail(orderDetailBean.getOrderId());
        EventBus.getDefault().post(new OrderListEvent());
    }

    @Override
    public void newOrderSuccess(String orderId) {
        mPresenter.getOrderDetail(orderId);
        EventBus.getDefault().post(new OrderListEvent());
    }

    @Subscribe
    public void onEvent(OrderDetailEvent event) {
        mPresenter.getOrderDetail(orderDetailBean.getOrderId());
    }

    @Subscribe
    public void onEvent(PayResultEvent event) {
        mPresenter.payQuery(payId, payType);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
